package com.icms.web.index;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheName;
import com.icms.common.basic.MemberController;
import com.icms.common.config.AppConfig;
import com.icms.common.config.AppConst;
import com.icms.common.ext.CacheInterceptor;
import com.icms.common.util.HtmlGeneratorUtil;
import com.icms.common.util.StrUtil;
import com.icms.core.model.Category;
import com.icms.core.model.Content;
import com.icms.core.model.Model;
import com.icms.core.model.ModelFiled;
import com.icms.core.model.Website;
import com.icms.core.service.CategoryService;
import com.icms.core.service.ContentService;
import com.icms.core.service.ModelFiledService;
import com.icms.core.service.ModelService;
import com.icms.core.service.SiteService;

/**
 * 首页控制器
 * 
 * @author Jin E-mail:jin@westboy.net
 * @version 创建时间：2016年4月22日 下午10:44:53
 */
public class IndexController extends MemberController {

	/**
	 * 首页分发
	 * 
	 * 首页:/ 频道:/news 列表:/news-list-pageId 内容:/news-content-Id
	 * 
	 */
	@Before(CacheInterceptor.class)
	@CacheName(AppConst.INDEX_CACHE)
	public void index() {
		String domain = getDomain();
		String channel = getPara(0);
		String action = getPara(1);
		Website site = SiteService.service.getWebsiteByDomain(domain);
		// 站点不存在
		if (site != null) {
			File file = new File(STATIC_HTML_PATH + site.getSiteId() + "/index.html");
			LogKit.debug("##########是否生成静态:" + file.exists() + "#################");
			if (file.exists()) {
				redirect("/html/" + site.getSiteId() + "/index.html");
				return;
			}
			// 如果当前站点存在,则设置title keyword...等属性
			setAttr("website", site.getSitename());
			setAttr("title", site.getTitle());
			setAttr("keyword", site.getKeyword());
			setAttr("description", site.getDescription());
			// 查询分类
			Category category = CategoryService.service.getCategoryBySiteIdAndCategoryName(site.getSiteId(), channel);
			System.out.println("site.getSiteId()" + site.getSiteId());
			// 设置頻道名称
			if (category != null) {
				setAttr("channelName", category.getCategoryName());
			}
			if (StrUtil.isBlank(channel)) {
				LogKit.info("请求类型：首页访问");
				home(site);
			} else if (category != null && StrUtil.isBlank(action)) {
				LogKit.info("请求类型：频道访问");
				channel(site, category);
			} else if (category != null && StrUtil.StrEquals(action, LIST)) {
				LogKit.info("请求类型：列表访问");
				list(site, category, channel);
			} else if (category != null && StrUtil.StrEquals(action, CONTENT)) {
				LogKit.info("请求类型：内容访问");
				content(site, category);
			} else {
				renderError(404);
			}
		} else {
			setAttr("errorMsg", "对不起，你访问的站点不存在！");
			setAttr("errorCode", "404");
			render("error.html");
		}
	}

	/**
	 * 首页
	 * 
	 * @param site
	 */
	private void home(final Website site) {
		// 判断是否为手机端访问
		if (isMobile() && site.getIsMobile()) {
			renderPath(site.getMobileTpl(), INDEX_TPL);
		} else {
			renderPath(site.getTemplate(), INDEX_TPL);
		}
	}

	/**
	 * 频道页面
	 * 
	 * @param site
	 * @param category
	 */

	private void channel(final Website site, final Category category) {

		if (category.getAlone()) {
			setAttr("content", category.getContent());
		}
		setAttr("categoryId", category.getCategoryId());
		setAttr("contentId", 2l);
		if (isMobile() && site.getIsMobile()) {
			renderPath(site.getMobileTpl(), category.getIndexTpl());
		} else {
			renderPath(site.getTemplate(), category.getIndexTpl());
		}

	}

	/**
	 * 列表页面
	 * 
	 * @param site
	 * @param category
	 * @param channel
	 */

	private void list(final Website site, final Category category, final String channel) {
		int pageNumber = getParaToInt(2, 1);
		Page<Content> page = ContentService.service.getContentPageByCatId(pageNumber, category.getCategoryId());
		setAttr("page", page);
		setAttr("categoryName", category.getShortname());
		setAttr("siteId", site.getSiteId());
		renderPath(site.getTemplate(), category.getListTpl());
	}

	/**
	 * 内容页面
	 * 
	 * @param site
	 * @param category
	 */
	private void content(final Website site, final Category category) {

		if (isMobile() && site.getIsMobile()) {
			renderPath(site.getMobileTpl(), category.getContentTpl());
		} else {
			renderPath(site.getTemplate(), category.getContentTpl());
		}
		renderText("你访问的内容页");
	}

	/**
	 * 搜索 m 和 c 为空表示关键字查询 m 和 c 不为空表示模型字段查询
	 */
	public void search() {
		String domain = getDomain();
		int modelId = getParaToInt("m");
		int pageNumber = getParaToInt("p", 1);
		long catId = getParaToLong("c");
		String keyWord = getPara("keyword");
		Map<String, Object> param = new HashMap<String, Object>();
		String action = AppConfig.HttpProtocol + "://" + domain + "/search?m=" + modelId + "&c=" + catId;
		if (modelId > 0 && catId > 0) {
			Website site = SiteService.service.getWebsiteByDomain(domain);
			Category category = CategoryService.service.getCategoryBySiteIdAndCategoryId(site.getSiteId(), catId);
			Model model = ModelService.service.getModelByModelId(modelId);
			List<ModelFiled> modelFileds = ModelFiledService.service.getModelFiledByModelId(modelId);
			// 循环检索获取filedName和fildValue
			for (ModelFiled filed : modelFileds) {
				String filedValue = getPara(filed.getFiledName());
				if (!StrUtil.isBlank(filedValue)) {
					param.put(filed.getFiledName(), filedValue);
					action += "&" + filed.getFiledName() + "=" + filedValue;
				}
			}
			// 查询输出
			Page<Record> page = ContentService.service.getContentByModelIdAndFiledNames(pageNumber,
					model.getTableName(), modelId, param);
			setAttr("page", page);
			setAttr("siteId", site.getSiteId());
			setAttr("param", param);
			setAttr("action", action);
			if (isMobile()) {
				renderPath(site.getMobileTpl(), StrUtil.isBlank(category.getListTpl())?(LIST_TPL+ "." + DEFAULT_HTML_SUFFIX):category.getListTpl());
			} else {
				renderPath(site.getTemplate(),category.getListTpl());
			}
		} else {
			if (StrUtil.isBlank(keyWord)) {
				renderText("请输入要查询的关键字");
				return;
			}
			renderText("全文检索！");
		}
	}

	public void htmlStatic() {

		HtmlGeneratorUtil html = new HtmlGeneratorUtil(this.getDomain(), 1);
		html.createHtmlPage(this.getDomain(), "index");
		renderText("htmlStatic");

	}

}